use std::env;

use diesel::{r2d2, Connection, MysqlConnection};
use dotenvy::dotenv;

pub mod table;
pub mod view;

mod crud;
mod schema;

pub type DbPool = r2d2::Pool<r2d2::ConnectionManager<MysqlConnection>>;
pub type DbError = Box<dyn std::error::Error + Send + Sync>;

#[allow(dead_code)]
pub fn establish_connection() -> MysqlConnection {
    dotenv().ok();
    let database_url = env::var("DATABASE_URL").expect("DATABSE_URL must be set");
    MysqlConnection::establish(&database_url)
        .unwrap_or_else(|_| panic!("Error connecting to {}", database_url))
}

pub fn initialize_db_pool() -> DbPool {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL should be set");
    let manager = r2d2::ConnectionManager::<MysqlConnection>::new(database_url);
    r2d2::Pool::builder()
        .build(manager)
        .expect("DATABASE_URL should be valid to mysql server")
}
